package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.Util.JwtUtil;
import com.qk.common.enums.LoginEnum;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.RoleService;
import com.qk.management.service.UserService;
import com.qk.vo.user.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @author: zyx
 * @created: 2025-10-07-19:37
 * @description:
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleService roleService;

    private static final String DEFAULT_PASSWORD_SUFFIX = "123";
    private static final Integer USER_STATUS_UNNORMAL = 0;

    @Override
    public PageResult<UserDO> page(String name, Integer status, String phone, Integer deptId, Integer page, Integer pageSize) {
        //开启分页
        PageHelper.startPage(page, pageSize);
        List<UserDO> users = userMapper.selectByPage(name, status, phone, deptId);
        //用hutool工具包对手机号进行脱敏
        users.forEach(user -> user.setPhone(DesensitizedUtil.mobilePhone(user.getPhone())));
        Page<UserDO> pageInfo = (Page<UserDO>) users;
        return new PageResult<>((int) pageInfo.getTotal(), pageInfo.getResult());
    }

    @Override
    public void addUser(User user) {
        //参数校验
        boolean hasNullField = BeanUtil.hasNullField(user, "id", "password", "roleId", "deptId", "image", "remark", "updateTime", "createTime");
        if (hasNullField) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        //补全参数
        String rawPassword = user.getPassword() + DEFAULT_PASSWORD_SUFFIX;
        user.setPassword(DigestUtils.md5DigestAsHex(rawPassword.getBytes()));
        user.setUpdateTime(LocalDateTime.now());
        user.setCreateTime(LocalDateTime.now());
        //插入
        userMapper.insert(user);
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    @Override
    public void updateUser(User user) {
        //参数校验
        boolean hasNullField = BeanUtil.hasNullField(user, "id", "password", "roleId", "deptId", "image", "remark", "updateTime", "createTime");
        if (hasNullField) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        // 设置更新时间为当前时间
        user.setUpdateTime(LocalDateTime.now());
        // 密码加密处理
        user.setPassword(DigestUtils.md5DigestAsHex((user.getPassword()+"123").getBytes()));
        userMapper.update(user);
    }

    @Override
    public List<User> listByRole(String roleLabel) {
        return userMapper.listByRole(roleLabel);
    }

    @Override
    public void deleteUsers(List<Integer> ids) {
        userMapper.deleteUsers(ids);
    }

    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        boolean hasNullField = BeanUtil.hasNullField(dto);
        if (hasNullField) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        //根据用户名获取用户信息
        User dbUser = userMapper.selectByUsername(dto.getUsername());
        if (Objects.isNull(dbUser)) {
            CommonException.throwCommonException(LoginEnum.USER_NOT_EXIST);
        }
        //用户状态校验
        if(ObjectUtil.equals(dbUser.getStatus(), USER_STATUS_UNNORMAL)){
            CommonException.throwCommonException(LoginEnum.USER_STATUS_UNNORMAL);
        }
        //获取前端传过来的密码并进行MD5处理
        String userPassword = DigestUtils.md5DigestAsHex((dto.getPassword()).getBytes());
        if(!ObjectUtil.equals(userPassword, dbUser.getPassword())){
            CommonException.throwCommonException(LoginEnum.USER_PASSWORD_ERROR);
        }
        //封装为VO对象并返回
        //获取用户角色
        HashMap<String, Object> claims= new HashMap<>();
        claims.put("id", dbUser.getId());
        claims.put("username", dbUser.getUsername());
        Role role = roleService.getById(dbUser.getRoleId());
        return UserLoginVO.builder()
                .id(dbUser.getId())
                .username(dbUser.getUsername())
                .name(dbUser.getName())
                .image(dbUser.getImage())
                .roleLabel(role.getLabel())
                //生成token
                .token(JwtUtil.generateToken(claims))
                .build();
    }
}
